<template>
    <div>
        <el-card class="login-box">
            <h3>登录</h3>
            <el-form :rules="userFormRules" :model="userForm" ref="loginForm">
                <el-form-item prop="username">
                    <el-input  prefix-icon="el-icon-user-solid" v-model="userForm.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input  prefix-icon="el-icon-s-goods" show-password v-model="userForm.password"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="loginbtn" @click="login()">登录</el-button>
                </el-form-item>
            </el-form>
           没有账号，<router-link to="/register">请注册</router-link>
        </el-card>
    </div>
    <!-- 

        vue2操作DOM的步骤
        1、给要操作目标元素添加一个ref属性，然后属性中写上值
        ref="xx"
        2、直接在vue实例上$refs
     -->
</template>


<script>
import {setStore} from '@/util/h5store'
import {TOKEN_KEY} from '@/util/constant'
import {mapActions} from 'vuex'
export default {
    data(){
        return{
            userForm:{
                username:'',
                password:''
            },
            userFormRules:{
                username:[
                    {required:true,message:'用户名不能为空',trigger:'blur'},
                    {min:3,max:12,message:'用户名长度介于3-12位之间',trigger:'blur'}
                ],
                password:[
                    {required:true,message:'密码不能为空',trigger:'blur'},
                    {min:3,max:12,message:'密码长度介于3-12位之间',trigger:'blur'}
                ]
            }
        }
    },
    methods:{
        ...mapActions({"guia":"getUserInfoAsync"}),
        login(){
            //在表单元素中有一个validate方法
            this.$refs.loginForm.validate(async args=>{
                
               if(args){
                 const {code,message,token}=await this.$api.users.login(this.userForm)
                 if(code){
                    //this.$message.success(message)
                    this.$message({
                        message,
                        type:'success'
                    })
                    //保存token
                    setStore(TOKEN_KEY,token)
                    //根据token来查询用户信息
                    //访问状态机中的异步方法来获取用户的信息
                    this.guia()
                    this.$router.replace('/')
                 }else{
                    this.$message.warning(message)
                 }
               }
            })

        }
    }
}
</script>

<style lang="scss">
    .login-box{
        margin: 200px auto;
        width: 480px;
        .loginbtn{
            width: 450px;
        }
    }
</style>